﻿namespace OboutInc.EasyMenu_Pro.Designer
{
    using OboutInc.EasyMenu_Pro;
    using System;
    using System.Collections;
    using System.ComponentModel.Design;
    using System.Reflection;

    public class EasyMenuItemsEditor : CollectionEditor
    {
        public EasyMenuItemsEditor(Type type) : base(type)
        {
        }

        protected override object CreateInstance(Type itemType)
        {
            object obj2 = base.CreateInstance(itemType);
            ((EasyMenu) base.Context.Instance).CSSClassesCollection.Add(new CSSClasses(itemType));
            return obj2;
        }

        protected override Type[] CreateNewItemTypes()
        {
            ArrayList list = new ArrayList();
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    foreach (Module module in assembly.GetModules(false))
                    {
                        list.AddRange(module.FindTypes(new TypeFilter(EasyMenuItemsEditor.MyClassFilter), typeof(ItemBase)));
                    }
                }
                catch
                {
                }
            }
            this.uniqueList(list);
            Type[] typeArray = new Type[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                typeArray[i] = (Type) list[i];
            }
            return typeArray;
        }

        protected override void DestroyInstance(object instance)
        {
            ((EasyMenu) base.Context.Instance).Components.removeUnusedClasses();
            base.DestroyInstance(instance);
        }

        public static bool MyClassFilter(Type typeObj, object criteriaObj)
        {
            return typeObj.IsSubclassOf((Type) criteriaObj);
        }

        private void uniqueList(ArrayList list)
        {
            list.Sort(new ClassComparer());
            int index = 1;
            while (index < list.Count)
            {
                if (((Type) list[index]).Name.Equals(((Type) list[index - 1]).Name))
                {
                    list.RemoveAt(index);
                }
                else
                {
                    index++;
                }
            }
        }

        public class ClassComparer : IComparer
        {
            int IComparer.Compare(object x, object y)
            {
                return ((Type) x).Name.CompareTo(((Type) y).Name);
            }
        }
    }
}

